#!/usr/bin/env python
#-*- coding: UTF-8 -*-

import urllib2

import config

class weibo:
	def __init__(self, db, users):
		self.db = db
		self.users = users;

	def __del__(self):
		pass

	def cache(self, uid, weibos):
		if len(weibos) == 0:
			return
		
		user = self.users.get(uid)
		max_weibo_id = weibos[0]['id']
		min_weibo_id = weibos[-1]['id']
		
		if user['max_weibo_id'] < max_weibo_id:
			user['max_weibo_id'] = max_weibo_id
			
		if user['min_weibo_id'] == 0 or user['min_weibo_id'] > min_weibo_id:
			user['min_weibo_id'] = min_weibo_id
		
	def load(self, uid):
		weibos = []
		try:
			vars = {'uid': uid}
			rows = self.db.select('cache_weibos', vars,
						what='id,poster_name,poster_icon,post_date,reposts_count,comments_count,content',
						where='uid=$uid', order='id DESC', limit=75)

			for r in rows:
				weibos.append({'id': r['id'], 
							   'poster_name': r['poster_name'], 
							   'poster_icon': r['post_date'],
							   'reposts_count': r['reposts_count'], 
							   'comments_count': r['comments_count'], 
							   'content': r['content']})
		except Exception as e:
			print 'weibos.load() except: %s' % (e.message)

		return weibos

	def refresh(self, uid, min_weibo_id):	
		user = self.users.get(uid)
		if not user:
			return []
		
		url = 'https://api.weibo.com/2/statuses/friends_timeline.json?access_token=%s&since_id=%d&count=25' % (user['token'], min_weibo_id)
		request = urllib2.urlopen(url)
		if request.getcode() != 200:
			return []

		weibos = []
		result = json.JSONDecoder().decode(request.read())
		for status in result['statuses']:
			weibos.append({'id': status['id'],
						   'poster_name': status['poster_name'],
						   'poster_icon': status['poster_icon'],
						   'post_date': status['created_at'],
						   'reposts_count': int(status['reposts_count']),
						   'comments_count': status['comments_count'],
						   'content': status['text']})

		self.cache(uid, weibos)
		return weibos
		
	def loadmore(self, uid, max_weibo_id):
		user = self.users.get(uid)
		if not user:
			return []

		if user['min_weibo_id'] >= max_weibo_id:
			url = 'https://api.weibo.com/2/statuses/friends_timeline.json?access_token=%s&max_id=%d&count=25' % (user['token'], max_weibo_id-1)
			request = urllib2.urlopen(url)
			if request.getcode() != 200:
				return []

		weibos = []
		result = json.JSONDecoder().decode(request.read())
		for status in result['statuses']:
			weibos.append({'id': status['id'],
						   'poster_name': status['poster_name'],
						   'poster_icon': status['poster_icon'],
						   'post_date': status['created_at'],
						   'reposts_count': int(status['reposts_count']),
						   'comments_count': status['comments_count'],
						   'content': status['text']})

		self.cache(uid, weibos)
		return weibos
